package me.leiusual.sharing.repository.datasource

import androidx.lifecycle.MutableLiveData
import androidx.paging.PageKeyedDataSource
import io.reactivex.observers.DisposableSingleObserver
import me.leiusual.sharing.api.ApiSharing
import me.leiusual.sharing.api.model.UserMessage
import me.leiusual.sharing.repository.model.Data
import timber.log.Timber

/**
 * author: leiusual
 * create on: 2019-08-04
 * description:
 */
class UserMessageDataSource(
    private val apiSharing: ApiSharing
) : PageKeyedDataSource<Int, UserMessage>() {

  val loadInitial = MutableLiveData<Data<Unit>>()

  override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, UserMessage>) {
    apiSharing.userMessageQuery(0, params.requestedLoadSize)
        .subscribe(object : DisposableSingleObserver<List<UserMessage>>() {
          override fun onStart() {
            loadInitial.postValue(Data.Loading())
          }

          override fun onError(e: Throwable) {
            loadInitial.postValue(Data.Error(e))
          }

          override fun onSuccess(t: List<UserMessage>) {
            loadInitial.postValue(Data.Success(Unit))

            callback.onResult(t, null, 1)
          }
        })
  }

  override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, UserMessage>) {
    // ignore
  }

  override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, UserMessage>) {
    apiSharing.userMessageQuery(params.key, params.requestedLoadSize)
        .subscribe(object : DisposableSingleObserver<List<UserMessage>>() {

          override fun onError(e: Throwable) {
            Timber.w(e)
          }

          override fun onSuccess(list: List<UserMessage>) {
            callback.onResult(list, if (list.size == params.requestedLoadSize) params.key + 1 else null)
          }
        })
  }
}